<!--
 * @Author: wjk
 * @Date: 2020-11-27 16:39:00
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-24 17:17:55
 * @description: file content
-->
<template>
  <base-page-view class-name="tab-container moments-container">
    <!-- header -->
    <view class="sticky-wrap header">
      <view class="search-line">
        <view class="user-center-icon" @click="toUserCenter">
          <template v-if="token && userInfo">
            <b-image v-if="userInfo.head_img" is-head width="50" height="50" class-name="user-icon" :src="userInfo.head_img" mode="aspectFit" />
            <image v-else class="user-icon" src="/static/images/app_logo.png" mode="aspectFit" />
          </template>
          <image v-else class="user-icon" src="/static/images/user_logout.png" mode="aspectFit" />
        </view>
        <view class="sub-item" @click="toSearch">
          <search-bar ref="search-bar" :placeholder="'想找的素材圈都在这里'" background="#F5F5F6" disabled></search-bar>
        </view>
        <view class="shy-icon-control" @click="groupClick('', 'shaixuan', 'Strick')">
          <image class="shy-icon" src="/static/images/icon/icon_material_shaixuan.png" mode="aspectFit" /> 筛选
        </view>
      </view>
      <horizontalList v-if="groupList && groupList.length" ref="group-list" :other-params="{listQuery: listQuery, filterItem: filterItem}" list-name="group" :click-emit-index="1" need-click :list="groupList" @itemClick="groupClick">
        <template v-slot="{item, otherParams}">
          <view :key="item.id" :class="{ active: otherParams.listQuery.attention === 1 ? item.title === '关注' : item.id === otherParams.listQuery.category_id || otherParams.filterItem.parent_id === item.id }">
            {{ item.title }}
          </view>
        </template>
      </horizontalList>
      <view v-if="filterItem.title" class="filter-select-box">
        <view class="filter-select-item" @click="setFilterBlur">
          {{ filterItem.title }}
          <view class="close">X</view>
        </view>
      </view>
    </view>
    <!-- 在全部分类下且未筛选时，显示banner和channel-list -->
    <template v-if="isAllGroup && !filterItem.title">
      <!-- banner模块 -->
      <view v-if="bannerList && bannerList.length" class="banner-block">
        <base-swiper autoplay mode="aspectFill" :style-obj="'height:'+bannerHeight+'px'" :swiper-list="bannerList" border-radius="0rpx" @itemClick="bannerClick"></base-swiper>
      </view>
      <!-- channel列表 -->
      <horizontalList v-if="channnelList && channnelList.length" ref="channel-list" list-name="channel" :list="channnelList" need-click :click-just="false" @itemClick="setChannel">
        <template v-slot="{item}">
          <view class="item-image">
            <image :src="item.icon || '/static/images/icon/icon_share_circle.png'" mode="aspectFit" />
          </view>
          <view class="item-text">{{ item.title }}</view>
        </template>
      </horizontalList>
    </template>

    <!-- 文章列表 -->
    <view class="article-list">
      <article-list :article-list="articleList" @initShare="changeShareOption" />
    </view>
    <view style="background-color: white">
      <base-list-state :list-length="listLength" :list-query="{page_no: listQuery.page_no, page_size: listQuery.page_size}" :list-state="listState" :list-empty="listEmpty" />
    </view>
    <!-- 为你推荐列表 -->
    <view v-if="!listLength && groupList.length && !listState.loading" style="min-height: 50vh">
      <recommend v-if="listQuery.attention === 1" ref="recommend"></recommend>
    </view>
    <!-- 筛选弹窗 -->
    <filter-list ref="filterList" @selectFilter="selectFilter">
      <horizontalList v-if="channnelList && channnelList.length" ref="channel-list" list-name="channel" :list="channnelList" need-click :click-just="false" @itemClick="setChannel">
        <template v-slot="{item}">
          <view class="item-image">
            <image :src="item.icon || '/static/images/icon/icon_share_circle.png'" mode="aspectFit" />
          </view>
          <view class="item-text">{{ item.title }}</view>
        </template>
      </horizontalList>
    </filter-list>
    <!-- <view class="share-icon" :class="{ active: showShareIcon }" @click="showSharePop">
      <image src="/static/images/icon/icon_share_circle.png" mode="aspectFit" />
    </view> -->
    <share ref="sharePop" :share-option="shareOption" />

    <view class="pubilsh-button" :class="{ active: showShareIcon }" @click="toPublishPage">
      <b-image width="250" height="80" is-asset src="/static/images/material/icon_publish.png" />
    </view>
  </base-page-view>
</template>
<script>
import { mapState } from 'vuex'
import baseSwiper from '@/components/base/base-swiper.vue'
import share from '@/components/draw/share'
import searchBar from '@/components/searchBar/index'
import filterList from './components/filter-list'
import ArticleList from './components/article-list'
import recommend from './components/recommend'
import horizontalList from '@/components/horizontalList/index'
import { debounce } from '@/utils/tools'
import { toFunctionDetail, h5NavigateTo } from '@/utils/navigateTo'
import './index.scss'
export default {
  name: 'Moments',
  components: {
    baseSwiper,
    searchBar,
    filterList,
    horizontalList,
    share,
    recommend,
    ArticleList
  },
  data() {
    return {
      shareBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/share/`,
      channnelList: [],
      bannerHeight: 100,
      bannerList: [],
      filterItem: {}, // 筛选选中对象
      groupList: [], // 分类列表
      isAllGroup: true,
      shareOption: {},
      articleList: [], // 文章列表
      showShareIcon: true,
      scrollTop: 0,
      listQuery: {
        category_id: 1,
        materialType: '',
        page_no: 1,
        page_size: 10,
        searchKey: '',
        type: '' // 素材类型：2 - 单图,4 - 多图,8 - 视频, 10 - 文章，12 - 产品
      },
      listState: {
        loading: true,
        more: true
      },
      listEmpty: { type: 'empty_list', text: '暂无数据' }
    }
  },
  computed: {
    listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.articleList.length
    },
    ...mapState([
      'token',
      'userInfo'
    ])
  },
  onShow() {
    this.fetchData()
  },
  onReady() {},
  onPageScroll(e) {
    this.scrollTop = e.scrollTop
    this.showShareIcon = false
    clearInterval(this.shareTimer)
    this.shareTimer = setTimeout(() => {
      this.showShareIcon = true
    }, 500)
  },
  onPullDownRefresh() {
    setTimeout(() => {
      this.listQuery.page_no = 1
      this.fetchData()
      uni.stopPullDownRefresh()
    }, 500)
  },
  onReachBottom: debounce(function() {
    if (!this.listLength && this.$refs.recommend) {
      this.$refs.recommend.loadMore()
    } else if (this.listState.more) {
      this.listQuery.page_no++
      this.fetchList()
    }
  }, 500),
  onShareAppMessage(res) {
    return this.$queryShareOption(res, this.shareOption)
  },
  methods: {
    async fetchData() {
      const res = await this.$api.materialApi.getMaterialCategory()
      if (res.success) {
        this.channnelList = res.data.top_categorys || []
        this.bannerList = res.data.banners || []
        this.groupList = res.data.sencond_categorys || []
        if (this.bannerList && this.bannerList.length) {
          uni.getImageInfo({
            src: this.bannerList[0].pic,
            success: (res) => {
              const picHeight = this.systemInfo.screenWidth * res.height / res.width
              this.bannerHeight = picHeight
            }
          })
        }
        this.fetchList()
      }
    },
    async fetchList() {
      this.listState.loading = true
      const res = await this.$api.materialApi.getCategoryMaterial(this.listQuery)
      if (res.success) {
        if (this.listQuery.page_no === 1) {
          this.articleList = []
          this.listState.more = true
        }
        this.articleList = this.articleList.concat(res.data)
        if (res.data.length < this.listQuery.page_size) {
          this.listState.more = false
        }
      }
      this.listState.loading = false
    },
    getActive(item) {
      if (!item) return
      if (this.listQuery.attention === 1) {
        return item.title === '关注'
      }
      return item.id === this.listQuery.category_id || this.filterItem.parent_id === item.id
    },
    changeShareOption(res) {
      this.shareOption = res
    },
    showSharePop() {
      if (this.token) {
        this.$refs.sharePop.show(this.shareOption)
      } else {
        this.$navigateTo('/pages/login/index')
      }
    },
    toSearch() {
      this.$navigateTo(`/pages/moments/search`)
    },
    setChannel(index) {
      console.log(index, 777)
      const channel = this.channnelList[index]
      if (this.$refs.filterList) {
        this.$refs.filterList.closePopup()
      }
      // 2-产品模板, 3-文章模板
      if (channel.have_url) {
        uni.setStorageSync('webViewTitle', channel.title)
        h5NavigateTo(channel.direct_url)
      } else if (channel.template_type === 2) {
        this.$navigateTo(`/pagesMaterial/product/index?id=${channel.id}&title=${channel.title}`)
      } else if (channel.template_type === 3) {
        this.$navigateTo(`/pagesMaterial/article/index?id=${channel.id}&title=${channel.title}`)
      }
    },
    bannerClick(obj) {
      const item = obj.item
      if (!item) return
      if (item.jumpType === 1) {
        console.log('item', item)
        return
      } else if (item.jumpType === 2) {
        const url = item.type_val ? item.type_val : item.typeVal
        h5NavigateTo(url)
      } else {
        item.type_val = item.type_val ? item.type_val : item.typeVal
        item.from_type = item.from_type ? item.from_type : item.fromType
        item.activity_id = item.activity_id ? item.activity_id : item.activityId
        toFunctionDetail(item)
      }
    },
    toUserCenter() {
      if (!this.token) {
        this.$navigateTo('/pages/login/index')
        return
      }
      this.$navigateTo('/pagesMaterial/user-center/index')
    },
    toPublishPage() {
      if (!this.token) {
        this.$navigateTo('/pages/login/index')
        return
      }
      this.$navigateTo('/pagesMaterial/publish/index?from=moment')
    },
    groupClick(index, type, Strick) {
      if (type === 'shaixuan') {
        this.$refs.filterList.showPopUp(this.listQuery.category_id)
        return
      }
      const item = this.groupList[index]
      if (item.title === '关注' && !this.token) {
        this.$navigateTo('/pages/login/index')
        return
      }
      if ((this.isAllGroup && item.title !== '全部') || (!this.isAllGroup && item.title === '全部')) {
        this.articleList = []
      }
      this.isAllGroup = item.title === '全部'
      this.listQuery.category_id = item.id
      this.listQuery.attention = item.title === '关注' ? 1 : 2
      this.listQuery.page_no = 1
      this.listQuery.type = ''
      this.filterItem = {}
      this.$refs.filterList.clear()
      this.fetchList()
      setTimeout(() => {
        uni.stopPullDownRefresh()
      }, 500)
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    },
    selectFilter(item) {
      if (item.id) {
        this.listQuery.category_id = item.id
        this.listQuery.type = ''
        if ((this.isAllGroup && item.title !== '全部') || (!this.isAllGroup && item.title === '全部')) {
          this.articleList = []
        }
        this.isAllGroup = false

        if (item.title !== '全部') {
          this.filterItem = { ...item }
        } else if (this.listQuery.attention === 1) {
          this.filterItem = { ...item }
          this.groupList.map(item => {
            if (this.filterItem.id === item.id) {
              this.filterItem.title = item.title
            }
          })
        } else {
          this.filterItem = {}
        }

        if (this.$refs['group-list'] && this.listQuery.attention !== 1) {
          const index = this.groupList.findIndex(i => i.id === (item.parent_id || item.id))
          this.$refs['group-list'].setIndex(index)
        }
      }
      if (item.isType) {
        if (this.listQuery.attention === 1) {
          this.listQuery.category_id = -1
        } else if (this.filterItem && this.filterItem.id) {
          this.listQuery.category_id = this.filterItem.parent_id
        }
        if (item.type) {
          this.filterItem = { ...item }
        } else {
          // this.filterItem = { }
        }
        this.listQuery.type = item.type || ''
      }
      this.listQuery.page_no = 1
      this.fetchList()
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    },
    setFilterBlur() {
      this.listQuery.category_id = this.filterItem.parent_id || 1
      this.listQuery.type = ''
      this.filterItem = {}
      this.listQuery.page_no = 1
      if (this.listQuery.attention === 1) {
        this.listQuery.category_id = -1
      }
      this.$refs.filterList.clear()
      this.fetchList()
    },
    initShare() {
      if (this.token) {
        this.shareOption.share_url = ''
        this.showShare()
      } else {
        this.hideShare()
      }
    }
  }
}
</script>
